// merge6.hxx


#ifndef _BLOGS_MERGE6
#define _BLOGS_MERGE6


#include <type_traits>

#include "array.hxx"
#include "comparable.hxx"


namespace blogs
{


class Merge6
{

  private:

    template
    <
        class _T,
        class = typename std::enable_if<std::is_base_of<Comparable<_T>, _T>::value>::type
    >
    static
    bool
    __less__(_T const& v, _T const& w)
    {
        return v.compare_to(w) < 0;
    }


    template
    <
        class _T,
        class = typename std::enable_if<std::is_base_of<Comparable<_T>, _T>::value>::type
    >
    static
    void
    __sort__(int K, Array<_T> & a, int lo, int hi, Array<_T> & aux)
    {
        if (hi <= lo) return;
        int N = hi - lo + 1;
        Array<int> s(K), e(K);  // start and end indices for subarrays
        int sz = int(std::ceil(double(N) / K));
        for (int i = 0; i < K; ++i) {
            s[i] = lo + i * sz;
            e[i] = (s[i] + sz - 1 < hi) ? s[i] + sz-1 : hi;
        }
        for (int i = 0; i < K; ++i)
            __sort__(K, a, s[i], e[i], aux);
        __merge__(K, a, s, e, aux);
    }


    template
    <
        class _T,
        class = typename std::enable_if<std::is_base_of<Comparable<_T>, _T>::value>::type
    >
    static
    void
    __merge__(int K, Array<_T> & a, Array<int> & s, Array<int> & e, Array<_T> & aux)
    {
        for (int i = s[0]; i <= e[K-1]; ++i)
            aux[i] = a[i];
        for (int i = s[0], min; i <= e[K-1]; ++i) {
            min = s[0];
            for (int k = 0; k < K; ++k)
                if (s[k] <= e[k] && __less__(aux[s[k]], aux[min]))
                    min = s[k], ++s[k];
            a[i] = aux[min];
        }
    }


  public:

    template
    <
        class _T,
        class = typename std::enable_if<std::is_base_of<Comparable<_T>, _T>::value>::type
    >
    static
    void
    sort(int K, Array<_T> & a)
    {
        Array<_T> aux = Array<_T>(a.size());
        __sort__(K, a, 0, a.size()-1, aux);
    }


    template
    <
        class _T,
        class = typename std::enable_if<std::is_base_of<Comparable<_T>, _T>::value>::type
    >
    static
    bool
    is_sorted(Array<_T> const& a)
    {
        int N = a.size();
        for (int i = 1; i < N; ++i)
            if (__less__(a[i], a[i-1])) return false;
        return true;
    }

};


} // end of namespace blogs


#endif

